package com.hymjweb.demo.config.beetl;

import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.ext.spring.BeetlSpringViewResolver;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置Beetl模板引擎
 */
@Configuration
public class BeetlConf {

    @Value("templates")
    String templatesPath;// 模板根目录

    @Bean(name = "beetlConfig")
    public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration(){
        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration=new BeetlGroupUtilConfiguration();
        // 获取Spring Boot的ClassLoader
        ClassLoader loader=Thread.currentThread().getContextClassLoader();
        if(loader==null){
            loader=BeetlConf.class.getClassLoader();
        }
        ClasspathResourceLoader cploader=new ClasspathResourceLoader(loader,templatesPath);
        beetlGroupUtilConfiguration.setResourceLoader(cploader);
        beetlGroupUtilConfiguration.init();

        // 设置SpringBoot的Shiro标签
        GroupTemplate groupTemplate = beetlGroupUtilConfiguration.getGroupTemplate();
        groupTemplate.registerFunctionPackage("so",new ShiroExt());
        //如果使用了优化编译器，涉及到字节码操作，需要添加ClassLoader
        groupTemplate.setClassLoader(loader);
        return beetlGroupUtilConfiguration;
    }

    @Bean(name = "beetlSpringViewResolver")
    public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration){
        BeetlSpringViewResolver beetlSpringViewResolver=new BeetlSpringViewResolver();
        beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
        beetlSpringViewResolver.setOrder(0);
        beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration);
        // 设置视图文件名后缀
        beetlSpringViewResolver.setSuffix(".html");
        return beetlSpringViewResolver;
    }

}
